package cn.nexd.app.presenter;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import cn.nexd.app.NexdApplication;
import cn.nexd.app.activity.inter.IMainActivityView;
import cn.nexd.app.activity.inter.IMallView;
import cn.nexd.app.activity.inter.ISearchActivityView;
import cn.nexd.app.arsenal.R;
import cn.nexd.app.model.ExpandableModel;
import cn.nexd.app.model.MallModel;
import cn.nexd.app.okhttp.Call;
import cn.nexd.app.okhttp.Response;
import cn.nexd.app.okhttp.android.OkHttpUtils;
import cn.nexd.app.okhttp.android.callback.Callback;
import cn.nexd.app.presenter.inter.IMallPresenter;
import cn.nexd.app.util.FileUtil;
import cn.nexd.app.util.UrlUtil;

/**
 * Created by xun on 2016/5/10.
 */
public class IMallPresenterImpl implements IMallPresenter {
    private Context context;
    private IMallView iMallView;
    private String mallInfoPath;

    public IMallPresenterImpl(Context context, IMallView iMallView) {
        this.context = context;
        this.iMallView = iMallView;
        this.mallInfoPath = new StringBuffer().append(NexdApplication.BASE_FILE_PATH)
                .append(File.separator)
                .append(NexdApplication.CONFIG)
                .append(File.separator)
                .append(NexdApplication.MALL_CONFIG).toString();
    }

    @Override
    public void checkIsFileIsExist() {
        if (!FileUtil.checkExist(mallInfoPath)) {
            updateMallInfo();
        } else if (FileUtil.checkExist(mallInfoPath)) {
            readMallInfo();
        }
    }

    @Override
    public void readMallInfo() {
        Log.d("mallConfigPath", mallInfoPath);
        try {
            String malls = FileUtil.readFileByLines(mallInfoPath);
            Log.d("MallConfig", malls);
            if ("".equals(malls)) {
                if (iMallView instanceof IMainActivityView) {
                    iMallView.showToast(context.getString(R.string.code_error_local_no_data));
                    return;
                } else if (iMallView instanceof ISearchActivityView) {
                    iMallView.showToast(context.getString(R.string.code_error_local_no_data_refresh));
                }
            } else {
                if (NexdApplication.malls != null && NexdApplication.malls.size() != 0) {
                    NexdApplication.malls.clear();
                }
                JSONArray mallsArray = new JSONArray(malls);
                String lastCityName = "";
                ArrayList<MallModel> mallModels = null;
                for (int i = 0; i < mallsArray.length(); i++) {
                    JSONObject jsonObject = mallsArray.getJSONObject(i);
                    MallModel mallModel = new MallModel();
                    if ("".equals(lastCityName)) {
                        mallModels = new ArrayList<MallModel>();
                        mallModel.setCnCityName(jsonObject.getString("cnCityName"));
                        mallModel.setMallName(jsonObject.getString("cnName"));
                        mallModel.setMallId(jsonObject.getString("buildingCode"));
                        mallModel.setPyCityName(jsonObject.getString("pyCityName"));
                        mallModel.setPyName(jsonObject.getString("pyName"));
                        mallModels.add(mallModel);
                        lastCityName = jsonObject.getString("cnCityName");
                    } else if (lastCityName.equals(jsonObject.getString("cnCityName"))) {
                        mallModel.setCnCityName(jsonObject.getString("cnCityName"));
                        mallModel.setMallName(jsonObject.getString("cnName"));
                        mallModel.setMallId(jsonObject.getString("buildingCode"));
                        mallModel.setPyCityName(jsonObject.getString("pyCityName"));
                        mallModel.setPyName(jsonObject.getString("pyName"));
                        mallModels.add(mallModel);
                    } else {
                        NexdApplication.malls.add(new ExpandableModel(lastCityName, mallModels));
                        mallModels = new ArrayList<MallModel>();
                        mallModel.setCnCityName(jsonObject.getString("cnCityName"));
                        mallModel.setMallName(jsonObject.getString("cnName"));
                        mallModel.setMallId(jsonObject.getString("buildingCode"));
                        mallModel.setPyCityName(jsonObject.getString("pyCityName"));
                        mallModel.setPyName(jsonObject.getString("pyName"));
                        mallModels.add(mallModel);
                        lastCityName = jsonObject.getString("cnCityName");
                    }
                }
                NexdApplication.malls.add(new ExpandableModel(lastCityName, mallModels));
            }
        } catch (JSONException e) {
            MobclickAgent.reportError(context, e);
            iMallView.showToast(context.getString(R.string.code_error_json));
            e.printStackTrace();
        } catch (IOException e) {
            MobclickAgent.reportError(context, e);
            iMallView.showToast(context.getString(R.string.code_error_read_file));
            e.printStackTrace();
        }
    }


    @Override
    public void updateMallInfo() {
        StringBuilder updateMallUrl = new StringBuilder();
        updateMallUrl.append(UrlUtil.BASE_IP)
                .append("nexd/v1.0/map/getBuildings.do");
        Log.d("updateMallUrl", updateMallUrl.toString());
        OkHttpUtils.post().url(updateMallUrl.toString())
                .addParams("appKey", NexdApplication.APPKEY)
                .build()
                .execute(new Callback<String>() {
                    @Override
                    public String parseNetworkResponse(Response response) throws Exception {
                        String result = response.body().string();
                        String resultCode = "";
                        Log.d("mallResult", result);
                        if (!TextUtils.isEmpty(result)) {
                            JSONObject rstJson = new JSONObject(result);
                            if (rstJson.getBoolean("isSuccess")) {
                                if (FileUtil.checkExist(mallInfoPath)) {
                                    FileUtil.deleteFileOrDir(mallInfoPath);
                                }
                                FileUtil.buildFile(mallInfoPath);
                                FileUtil.writeFile(mallInfoPath, rstJson.getString("malls"));
                                readMallInfo();
                                resultCode = "success";
                            } else {
                                iMallView.showToast(rstJson.getString("msgCode"));
                                resultCode = "fail";
                            }
                        }
                        return resultCode;
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        MobclickAgent.reportError(context, e);
                        if (iMallView instanceof IMainActivityView) {
                            iMallView.showToast(context.getString(R.string.code_error_check_network));
                        } else if (iMallView instanceof ISearchActivityView) {
                            ((ISearchActivityView) iMallView).refreshComplete();
                            iMallView.showToast(context.getString(R.string.code_error_refresh));
                        }
                    }

                    @Override
                    public void onResponse(String response) {
                        if ("success".equals(response)) {
                            if (iMallView instanceof ISearchActivityView) {
                                ((ISearchActivityView) iMallView).refreshComplete();
                            }
                            if (iMallView instanceof IMainActivityView) {
                                iMallView.enterActivity();
                            }
                        } else if ("fail".equals(response)) {
                            iMallView.showToast(context.getString(R.string.error_service_no_data));
                        }
                    }
                });
    }


}
